import { defineStore } from "pinia";
import {
  type cacheType,
  store,
  debounce,
  ascending,
  getKeyList,
  filterHiddenLinkRoute,
  resetRouter,
  constantMenus,
  formatAsyncRoutes,
  filterNoPermissionRoute,
  formatFlatteningRoutes
} from "../utils";
import { useMultiTagsStoreHook } from "./multiTags";
import { getConfig } from "@/config";
import { storageLocal } from "@pureadmin/utils";
import { getAsyncRoutes } from "@/api/user";

export const usePermissionStore = defineStore({
  id: "pure-permission",
  state: () => ({
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 整体路由（一维数组格式）
    flatteningRoutes: [],
    // 缓存页面keepAlive
    cachePageList: [],
    // 异步获取到的路由
    asyncRouteList: []
  }),
  actions: {
    /** 组装整体路由生成的菜单 */
    handleWholeMenus(routes: any[]) {
      this.wholeMenus = filterNoPermissionRoute(
        filterHiddenLinkRoute(ascending(constantMenus.concat(routes)))
      );
      console.log("wholeMenus", this.wholeMenus);
      this.flatteningRoutes = formatFlatteningRoutes(
        this.constantMenus.concat(routes)
      );
      console.log("flatteningRoutes", this.flatteningRoutes);
    },
    async loadRouter() {
      this.asyncRouteList = [];
      let asyncRouteList = [];
      const key = "async-routes";
      if (getConfig()?.CachingAsyncRoutes) {
        asyncRouteList = storageLocal().getItem(key) as any;
      }
      if (asyncRouteList.length === 0) {
        const res = await getAsyncRoutes();
        if (res.code === 200) {
          asyncRouteList.push(...res.data);
          if (getConfig()?.CachingAsyncRoutes) {
            storageLocal().setItem(key, res.data);
          }
        }
      }
      if (asyncRouteList && asyncRouteList?.length > 0) {
        this.asyncRouteList.push(...asyncRouteList);
        asyncRouteList = formatAsyncRoutes(asyncRouteList);
      }
      constantMenus.forEach(item => {
        asyncRouteList.push(item);
      });
      await resetRouter(asyncRouteList);
      this.handleWholeMenus(asyncRouteList);
    },
    cacheOperate({ mode, name }: cacheType) {
      const delIndex = this.cachePageList.findIndex(v => v === name);
      switch (mode) {
        case "refresh":
          this.cachePageList = this.cachePageList.filter(v => v !== name);
          break;
        case "add":
          this.cachePageList.push(name);
          break;
        case "delete":
          if (delIndex !== -1) {
            this.cachePageList.splice(delIndex, 1);
          }
          break;
      }
      /** 监听缓存页面是否存在于标签页，不存在则删除 */
      debounce(() => {
        let cacheLength = this.cachePageList.length;
        const nameList = getKeyList(useMultiTagsStoreHook().multiTags, "name");
        while (cacheLength > 0) {
          if (
            nameList.findIndex(
              v => v === this.cachePageList[cacheLength - 1]
            ) === -1
          ) {
            this.cachePageList.splice(
              this.cachePageList.indexOf(this.cachePageList[cacheLength - 1]),
              1
            );
          }
          cacheLength--;
        }
      })();
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.wholeMenus = [];
      this.cachePageList = [];
      this.flatteningRoutes = [];
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
